﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AliboboStockLib.date;
using System.IO;
using System.Collections;
using AliboboStockLib.webutil;

namespace AliboboStockLib.stockupdater.sbdetail
{
    public class OtcSBGetter
    {
        protected String getStorePath(DateTime d)
        {
            String ds = DateUtils.getPlanString(d);
            String path = @"d:\SBdata\tempotc\" + ds + @"\";
            Directory.CreateDirectory(path);
            return path;
        }
        protected String getTargetFileName(String code, DateTime d)
        {
            String path = getStorePath(d);
            return  path + code + ".csv";
        }
        public static String getURL()
        {
            return "http://www.gretai.org.tw/ch/stock/aftertrading/broker_trading/download_ALLCSV.php";

        }
        public bool getCSV(String code, DateTime date)
        {

            String fn=getTargetFileName(code, date);
            if (File.Exists(fn))
                return true;

            String url = getURL();
            Hashtable ps = new Hashtable();
            String ds=String.Format("{0}{1:D2}{2:D2}",date.Year-1911,date.Month,date.Day);
            ps.Add("fromw","0");
            ps.Add("numbern","100");
            ps.Add("curstk",code);
            ps.Add("stk_date",ds);

            Hashtable headerSet = new Hashtable();
            headerSet.Add("Referer", "http://www.gretai.org.tw/ch/stock/aftertrading/broker_trading/brokerBS.php");
            headerSet.Add("User-Agent","	Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1");
            headerSet.Add("Host","www.gretai.org.tw");
            headerSet.Add("Accept-Language",	"zh-tw,en-us;q=0.7,en;q=0.3");
            headerSet.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");


            String content = HttpPost.Request(url, ps, Encoding.UTF8, headerSet);
            if (content.StartsWith("Error"))
            {
                return false;
            }
            System.Diagnostics.Debug.WriteLine("交易日報表 Complete:"+code);

            File.WriteAllText(fn, content, Encoding.GetEncoding("big5"));
            File.WriteAllText(fn + ".utf8.csv", content, Encoding.GetEncoding("utf-8"));
            return true;

        }
        public void process(DateTime d)
        {
            List<String> allCodes = OtcSBDetailUpdater.getAllOtcCodes();
            
            foreach (String code in allCodes)
            {
                getCSV(code, d);
            }
        }
    }
}
